/***********************************************************
 * 文件名: PublicUtil.java<br>
 ********************************************************/
package com.springcloud.sc.ucpv5.client.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.nio.ByteBuffer;
import java.text.Collator;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import com.springcloud.sc.ucpv5.client.application.util.Constant;
import com.springcloud.sc.ucpv5.client.application.util.FrameworkUtil;
import com.springcloud.sc.ucpv5.client.application.util.LogFileCleaner;
import com.springcloud.sc.ucpv5.client.module.datamanager.LoginDataManager;
/**
 * 
 * PublicUtil
 * 
 * @author
 * @date 2006-7-20
 * @version
 */
public class PublicUtil {

	public static void saveObject(Serializable mgr, String fileName) {
		if (null == mgr) {
			return;
		}

		FileOutputStream outputStream = null;
		ObjectOutputStream out = null;

		try {
			File file = new File(fileName);
			if (!file.exists()) {
				if (file.getParentFile() != null)
					file.getParentFile().mkdirs();
				file.createNewFile();
			} else if (!file.canWrite()) {
				file.delete();
				file.createNewFile();
			}

			outputStream = new FileOutputStream(file);
			out = new ObjectOutputStream(outputStream);
			out.writeObject(mgr);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (null != out) {
					out.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	public static String toHex(int v) {
		String ret = Integer.toHexString(v);
		if (ret.length() == 1) {
			return "0" + ret;
		}
		return ret;
	}

	public static Serializable loadObject(Serializable defaultObj, String fileName) {
		File file = new File(fileName);
		if (!file.exists()) {
			return defaultObj;
		}

		Serializable retObj = defaultObj;
		FileInputStream stream = null;
		ObjectInputStream in = null;
		try {
			stream = new FileInputStream(file);

			in = new ObjectInputStream(stream);
			retObj = (Serializable) in.readObject();
		} catch (FileNotFoundException e) {
		} catch (IOException e) {
		} catch (ClassNotFoundException e) {
		} finally {
			try {
				if (null != in) {
					in.close();
				}
			} catch (IOException e) {
			}
		}

		return retObj;
	}

	public static String replace(String sourceString, String oldString, String newString) {
		int i = sourceString.indexOf(oldString);
		StringBuffer stringbuffer = new StringBuffer();
		if (i == -1)
			return sourceString;
		stringbuffer.append(sourceString.substring(0, i) + newString);
		if (i + oldString.length() < sourceString.length())
			stringbuffer.append(replace(sourceString.substring(i + oldString.length(), sourceString.length()), oldString, newString));
		return stringbuffer.toString();
	}

	public static String[] split(String sourceString, String splitString) {
		java.util.StringTokenizer st = new java.util.StringTokenizer(sourceString, splitString);
		String[] s = new String[st.countTokens()];
		int i = 0;
		while (st.hasMoreTokens()) {
			s[i] = st.nextToken();
			i++;
		}
		return s;
	}

	public static String path2LocalePath(String path) {
		String prefix = "resources" + "/" + "zh" + "/";

		path = path.replace('\\', '/');
		if (path.startsWith("/")) {
			path = path.substring("/".length());
		}
		if (!path.startsWith("resources/")) {
			path = prefix + path;
		} else {
			int index = path.indexOf("resources/");
			path = path.substring(index + "resources/".length());

			int localIndex = path.indexOf("zh/");
			if (localIndex != -1) {
				path = path.substring(localIndex + "zh/".length());
			}

			localIndex = path.indexOf("en/");
			if (localIndex != -1) {
				path = path.substring(localIndex + "en/".length());
			}
			// 转换为与local相关的路径
			path = prefix + path;
		}
		return path;
	}

	public static int nullToInt(Object obj) {
		return nullToInt(String.valueOf(obj));
	}

	public static int nullToInt(String s) {
		try {
			return Integer.parseInt(s);
		} catch (Exception e) {
			return 0;
		}
	}

	public static long nullToLong(String s) {
		return nullToInt(s);
	}

	public static byte nullToByte(String s) {
		try {
			return Byte.parseByte(s);
		} catch (Exception e) {
			return 0;
		}
	}

	public static short nullToShort(String s) {
		try {
			return Short.parseShort(s);
		} catch (Exception e) {
			return 0;
		}
	}

	public static double nullToDouble(Object obj) {
		return nullToDouble(obj + "");
	}

	public static double nullToDouble(String s) {
		try {
			return Double.parseDouble(s);
		} catch (Exception e) {
			return 0;
		}
	}

	public static boolean nullToBoolean(String s) {
		return s != null;
	}

	public static String nullToEmpty(Object obj) {
		return obj == null ? "" : String.valueOf(obj);
	}

	public static String toGBString(String s) {
		try {
			if (s == null)
				return "";
			return new String(s.getBytes("ISO8859_1"), "GBK");
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}
	}

	public static String toUTF8(String s) {
		try {
			if (s == null) {
				return "";
			}

			String ret = new String(s.getBytes("UTF-8"));
			return ret;
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}
	}

	public static String utf8ToUnicode(String s) {
		try {
			if (s == null) {
				return "";// ISO8859_1
			}

			String ret = new String((s).getBytes(), "UTF-8");
			return ret;
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}
	}

	public static String toCorbaEncode(String s) {
		try {
			if (s == null) {
				return "";
			}

			if (true) {
				return toUTF8(s);
			}
			return new String(s.getBytes(Constant.CORBA_ENCODING), "UTF-8");
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}
	}

	public static String toCorbaDecode(String s) {
		try {
			if (s == null) {
				return "";// ISO8859_1
			}
			if (true) {
				return utf8ToUnicode(s);
			}
			return new String(s.getBytes("UTF-8"), Constant.CORBA_ENCODING);
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}
	}

	private final static String CORBA_TRACE_FILE_NAME = "corbaMsg.log";
	private final static LogFileCleaner corbaLogCleaner = new LogFileCleaner(CORBA_TRACE_FILE_NAME, 500);

	public static void printCorbaObject(String msg, Object transferData) {
		if (true) {
			return;
		}
		try {
			StringBuffer buf = new StringBuffer();
			_unitCorbaPrint(transferData, buf, "");
			synchronized (CORBA_TRACE_FILE_NAME) {
				FileWriter writer = null;
				PrintWriter out = null;
				try {
					String prefix = PublicUtil.nullToEmpty(FrameworkUtil.getAbsolutePath(Constant.TRACE_DIRECTORY_PATH));
					String tracePath = "";
					if (prefix.equals("")) {
						tracePath = "log" + Constant.FILE_SEPARATOR + CORBA_TRACE_FILE_NAME;
					} else {
						tracePath = prefix + CORBA_TRACE_FILE_NAME;// 设置路径
					}
					final File dir = new File(tracePath).getParentFile();
					if (!dir.exists()) {
						dir.mkdirs();
					}

					File traceFile = new File(tracePath);

					if (!traceFile.exists()) {
						traceFile.createNewFile();
						corbaLogCleaner.filenew();
					} else if (traceFile.length() >= 102400) {// 100k
						String saveAsName = traceFile.getAbsolutePath() + "." + new Date().getTime();
						traceFile.renameTo(new File(saveAsName));
						traceFile.createNewFile();
						corbaLogCleaner.filenew();
					}

					writer = new FileWriter(traceFile, true);

					String time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(new Date()) + " ";
					out = new PrintWriter(writer);
					out.print(time);
					out.print(msg + "(opUser:" + LoginDataManager.getInstance().getName() + "):");
					out.println(buf.toString());
				} catch (Exception e) {
					e.printStackTrace(System.err);
				} finally {
					try {
						if (out != null) {
							out.close();
							out = null;
						}
						if (writer != null) {
							writer.close();
							writer = null;
						}
					} catch (IOException e) {
					}
				}
			}
		} catch (Throwable exp) {
			exp.printStackTrace();
		}
	}

	public static String toHexStr(int val) {
		StringBuffer buf = new StringBuffer();
		for (int i = 0; i < 4; ++i) {
			int tmp = ((val >> (i * 8)) & 0xff);
			buf.insert(0, _toHexStr(tmp));
		}
		return buf.toString();
	}

	private static String _toHexStr(int val) {
		StringBuffer buf = new StringBuffer(Integer.toHexString(val));
		for (int i = buf.length(); i < 2; ++i) {
			buf.insert(0, '0');
		}
		return buf.toString();
	}

	public static String toHexStr(short val) {
		StringBuffer buf = new StringBuffer();
		for (int i = 0; i < 2; ++i) {
			int tmp = ((val >> (i * 8)) & 0xff);
			buf.insert(0, _toHexStr(tmp));
		}
		return buf.toString();
	}

	public static String toHexStr(char val) {
		StringBuffer buf = new StringBuffer(Integer.toHexString(val));
		for (int i = buf.length(); i < 2; ++i) {
			buf.insert(0, '0');
		}
		return buf.toString();
	}

	public static String toHexStr(byte val) {
		int tmp = val >= 0 ? val : (val & 0x7f) + 0x80;
		StringBuffer buf = new StringBuffer(Integer.toHexString(tmp));
		for (int i = buf.length(); i < 2; ++i) {
			buf.insert(0, '0');
		}
		return buf.toString();
	}

	public static String byteToString(byte[] data) {
		StringBuffer buf = new StringBuffer("[");
		for (int i = 0; i < data.length; ++i) {
			buf.append(toHexStr(data[i]));
			buf.append(" ");
		}
		buf.append("]");
		return buf.toString();
	}

	public static void _unitCorbaPrint(Object transferData, StringBuffer buf, String levelPre) {
		if (null == transferData) {
			return;
		}

		buf.append(levelPre);
		buf.append(transferData.getClass().getName());
		buf.append("{\n");

		Field[] fields = transferData.getClass().getDeclaredFields();
		for (int i = 0; i < fields.length; ++i) {
			try {
				Field field = fields[i];

				Object data = field.get(transferData);
				if (data == null) {
					buf.append(levelPre + " ");
					buf.append(field.getName());
					buf.append(":null \n");
				} else if (data instanceof Number || data instanceof Boolean || data instanceof String) {
					buf.append(levelPre + " ");
					buf.append(field.getName() + ":");
					buf.append(data.toString());
					buf.append("\n");
				} else if (data instanceof Object[]) {
					Object[] array = (Object[]) data;
					if (array.length == 0) {
						buf.append(levelPre + " ");
						buf.append(field.getName());
						buf.append(":[] \n");
					} else {
						if (array[0] instanceof Number || array[0] instanceof Boolean || array[0] instanceof String) {
							buf.append(levelPre + " ");
							buf.append(field.getName());
							buf.append(":");
							buf.append(Arrays.toString(array));
							buf.append("\n");
						} else {
							buf.append(levelPre + " ");
							buf.append(field.getName());
							buf.append(":[");
							for (int j = 0; j < array.length; ++j) {
								_unitCorbaPrint(array[j], buf, levelPre + " ");
								buf.append(levelPre + ",");
							}
							buf.append("]\n");
						}
					}
				} else if (data.getClass().isArray()) {
					buf.append(levelPre + " ");
					buf.append(field.getName());
					buf.append(":");
					Class type = data.getClass().getComponentType();
					if ("byte".equalsIgnoreCase(type.getName())) {
						buf.append(byteToString((byte[]) data));
					} else if ("int".equalsIgnoreCase(type.getName())) {
						buf.append(Arrays.toString((int[]) data));
					} else if ("char".equalsIgnoreCase(type.getName())) {
						buf.append(Arrays.toString((char[]) data));
					} else if ("boolean".equalsIgnoreCase(type.getName())) {
						buf.append(Arrays.toString((boolean[]) data));
					} else if ("short".equalsIgnoreCase(type.getName())) {
						buf.append(Arrays.toString((short[]) data));
					} else if ("long".equalsIgnoreCase(type.getName())) {
						buf.append(Arrays.toString((long[]) data));
					} else if ("float".equalsIgnoreCase(type.getName())) {
						buf.append(Arrays.toString((float[]) data));
					}
					// buf.append(Arrays.toString((Array)data));
					buf.append("\n");
				} else {
					buf.append(levelPre + " ");
					buf.append(field.getName() + ":");
					buf.append(":\n");
					_unitCorbaPrint(data, buf, levelPre + " ");
				}
			} catch (IllegalArgumentException e) {
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			}

		}

		buf.append(levelPre);
		buf.append("}\n");
	}

	/**
	 * 转换交互对象以供前后台交互
	 * 
	 * @date 2006-7-21
	 * @param transferData
	 * @param isEcode
	 * @see
	 */
	public static void toCorbaString(Object transferData, boolean isEcode) {
		if (true)
			return;
		if (null == transferData) {
			return;
		} else if (transferData instanceof Object[]) {
			Object[] array = (Object[]) transferData;
			for (int j = 0; j < array.length; ++j) {
				if (array[j] instanceof Number || array[j] instanceof Boolean) {
					break;
				}
				toCorbaString(array[j], isEcode);
			}
		}

		if (transferData instanceof String) {
			String str = (String) transferData;
			transferData = isEcode ? toCorbaEncode(str) : toCorbaDecode(str);
			return;
		} else if (transferData instanceof Number || transferData instanceof Boolean) {
			return;
		}

		Field[] fields = transferData.getClass().getDeclaredFields();
		for (int i = 0; i < fields.length; ++i) {
			try {
				Field field = fields[i];

				Object data = field.get(transferData);
				if (data instanceof String) {
					String str = (String) data;
					if (null == str) {
						field.set(transferData, "");
						continue;
					}

					field.set(transferData, isEcode ? toCorbaEncode(str) : toCorbaDecode(str));
				} else if (null == data || data instanceof Number || data instanceof Boolean) {
					continue;
				} else {
					toCorbaString(data, isEcode);
				}
			} catch (IllegalArgumentException e) {
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			}

		}
	}

	/**
	 * 界面刷新线程同步执行接口 DispatchRunnable
	 * 
	 * @date 2006-8-11
	 * @version
	 */
	public static interface DispatchRunnable {
		Object run();

		boolean isInterrupted();
	}

	public static Object syncExec(final DispatchRunnable runnable, final int timeOut) {
		return syncExec(runnable, timeOut, true);
	}

	/**
	 * 同步调用，该方法会把鼠标设忙,同时调用界面刷新线程刷新界面
	 * 
	 * @date 2006-8-11
	 * @param runnable
	 * @param timeOut
	 *            :超时，如果为 <=0,无限等待,以毫秒为单位
	 * @Param bAutoBusy:是否自动处理鼠标设忙
	 * @return
	 * @see
	 */
	public static Object syncExec(final DispatchRunnable runnable, final int timeOut, final boolean bAutoBusy) {
		// 如果派发接口为空或者已经被中断，直接返回
		if (null == runnable || runnable.isInterrupted()) {
			return null;
		}

		final ExecutorService executor = Executors.newSingleThreadExecutor();
		final ArrayList list = new ArrayList();

		executor.execute(new Runnable() {
			@SuppressWarnings("unchecked")
			public void run() {
				Object retObj = null;
				try {
					retObj = runnable.run();
				} catch (Exception exp) {
				} catch (Throwable exp) {
				} finally {

					synchronized (list) {
						list.add(retObj);
						list.notifyAll();
					}
				}
			}

		});

		try {
			long startTime = System.currentTimeMillis();

			{
				synchronized (list) {
					try {
						list.wait(timeOut);
					} catch (InterruptedException e) {
						// TODO 自动生成 catch 块
						e.printStackTrace();
					}
				}
			}
		} finally {
			executor.shutdown();
		}

		return list.size() > 0 ? list.get(0) : null;
	}

	public static String toEncodeString(String s, String enc) {
		try {
			return java.net.URLEncoder.encode(s, enc);
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}
	}

	public static String toDecodeString(String s, String enc) {
		try {
			return java.net.URLDecoder.decode(s, enc);
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}
	}

	public static String filterString(String oldString) {
		return replace(oldString, "'", "''");
	}

	public static String getSubString(String oldString, int start) {
		int ender;
		String newString;
		ender = oldString.length();
		newString = oldString.substring(start, ender);
		return newString;
	}

	public static boolean isEmpty(String s) {
		return s == null || s.trim().equals("");
	}

	public static boolean isEmpty(Object object) {
		return isEmpty((String) object);
	}

	public static Date stringToDate(String s, String formatString) {
		try {
			return new SimpleDateFormat(formatString).parse(s);
		} catch (Exception e) {
			e.printStackTrace(System.err);
			return null;
		}
	}

	public static Calendar stringToCalendar(String s, String formatString) {
		Calendar cal = Calendar.getInstance();
		cal.setTime(stringToDate(s, formatString));
		return cal;
	}

	public static Map refClassMethod(Class refClass) {
		Map<String, Method> methodMap = new HashMap<String, Method>();
		Method[] methods = refClass.getMethods();
		for (int i = 0; i < methods.length; i++)
			methodMap.put(methods[i].getName(), methods[i]);
		return methodMap;
	}

	public static String formatDate(String dateString, String formatString) {
		int len = dateString.length();
		if (formatString.equals("year")) {
			if (len >= 4)
				return dateString.substring(0, 4) + "年";
		}
		if (formatString.equals("month")) {
			if (len >= 6)
				return dateString.substring(0, 4) + "年" + dateString.substring(4, 6) + "月";
		}
		if (formatString.equals("day")) {
			if (len >= 8)
				return dateString.substring(0, 4) + "年" + dateString.substring(4, 6) + "月" + dateString.substring(6, 8) + "日";
		}
		return dateString;
	}

	public static String formatDate(Object dateStr) {
		String dateString = dateStr.toString();
		String s = "";
		switch (dateString.length()) {
		case 4:
			s = formatDate(dateString, "year");
			break;
		case 6:
			s = formatDate(dateString, "month");
			break;
		case 8:
			s = formatDate(dateString, "day");
			break;
		}
		return s;
	}

	public static String dateToString(long m, String formatString) {
		return new SimpleDateFormat(formatString).format(new Date(m));
	}

	public static String dateToString(long m) {
		return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(m));
	}

	public static String dateToString(Date date) {
		return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date);
	}

	public static String nullToDate(Date d, String formatString) {
		String date = "";
		if (d == null)
			return "";
		try {
			date = new SimpleDateFormat(formatString).format(d);
		} catch (Exception e) {
			e.printStackTrace(System.err);
		}
		return date;
	}

	public static double transferStringToDouble(String sourceString, String splitString) {
		if (sourceString.indexOf(splitString) == -1)
			return nullToDouble(sourceString);
		String[] s = split(sourceString, splitString);
		return nullToDouble(s[0]);
	}

	public static String formatNumber(String srcStr, int nAfterDot) {
		if (srcStr == null || srcStr.equals(""))
			srcStr = "0";
		double d = nullToDouble(srcStr);
		char c[] = new char[nAfterDot];
		Arrays.fill(c, '0');
		java.text.DecimalFormat dformat = new java.text.DecimalFormat("0." + new String(c));
		return dformat.format(d);
	}

	public static String formatNumber(double srcStr, int nAfterDot) {
		double d = srcStr;
		char c[] = new char[nAfterDot];
		Arrays.fill(c, '0');
		java.text.DecimalFormat dformat = new java.text.DecimalFormat("0." + new String(c));
		return dformat.format(d);
	}

	public static String insertSingleQuot(String sourceString) {
		String regString = "([\\d]+)";
		return sourceString.replaceAll(regString, "'$1'");
	}

	public static String arrayToString(Object[] objArr) {
		if (objArr == null)
			return "";
		StringBuffer buffer = new StringBuffer("''");
		for (int i = 0; i < objArr.length; i++)
			buffer.append(",'" + objArr[i] + "'");
		return buffer.toString();
	}

	public static String arrayToStringNoQuote(Object[] objArr) {
		if (objArr == null)
			return "";
		StringBuffer buffer = new StringBuffer("");
		for (int i = 0; i < objArr.length; i++) {
			if (!buffer.toString().equals(""))
				buffer.append(",");
			buffer.append(objArr[i]);
		}
		return buffer.toString();
	}

	public static String listToString(List list) {
		if (list == null)
			return "";
		StringBuffer buffer = new StringBuffer("''");
		for (int i = 0; i < list.size(); i++)
			buffer.append(",'" + list.get(i) + "'");
		return buffer.toString();
	}

	public static String arrayToString(int[] intArr) {
		if (intArr == null)
			return "0";
		StringBuffer buffer = new StringBuffer("0");
		for (int i = 0; i < intArr.length; i++)
			buffer.append("," + intArr[i] + "");
		return buffer.toString();
	}

	public static String getNow() {
		return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
	}

	public static String byte2hex(byte[] b) {
		StringBuffer buffer = new StringBuffer("");

		try {
			for (int i = 0; i < b.length; i++) {
				// 因为toHexString()函数会首令b[i]先被转换为32位的整型，
				// 所以我们需要一个与运算，
				// 用于转换32位整型为8位（1个字节）的无符号整型。
				String stmp = Integer.toHexString(b[i] & 0XFF);
				if (stmp.length() == 1)
					buffer.append(" 0");
				else
					buffer.append(" ");

				buffer.append(stmp);
				// buffer.append(","+b[i]);
				if (buffer.length() % 256 == 0) {
					buffer.append("\n");
				}
			}
		} catch (Exception e) {
			System.err.println("HandleString.byte2hex Error，" + e.getMessage());
		}
		return buffer.toString();
	}

	public static byte[] hex2byte(String str) {
		int iLen = str.length();
		byte[] b = new byte[iLen / 2];
		String stmp = "";
		try {
			for (int i = 0; i < b.length; i++) {
				stmp = str.substring(i * 2, i * 2 + 2);
				b[i] = Integer.valueOf(stmp, 16).byteValue();
			}
		} catch (Exception e) {
			System.err.println("HandleString.hex2byte Error，" + e.getMessage());
		}
		return b;
	}

	public static boolean isInt(String source) {
		try {
			Integer.parseInt(source);
			return true;
		} catch (Exception e) {
			return false;
		}
	}

	public static boolean isNumber(String source) {
		try {
			Double.parseDouble(source);
			return true;
		} catch (Exception e) {
			return false;
		}
	}

	public static int toInt(String text) {
		if (text.startsWith("0x") || text.startsWith("0X")) {
			return Integer.parseInt(text.substring(2), 16);
		}
		return Integer.parseInt(text);
	}

	private final static String TRACE_DEBUG_FILE_NAME = "debug.log";
	private final static LogFileCleaner shakeHandLogCleaner = new LogFileCleaner(TRACE_DEBUG_FILE_NAME, 100);
	public final static int DEBUG_LEVEL_INFO = 100;
	public final static int DEBUG_LEVEL_MSG = 200;
	public final static int DEBUG_LEVEL_WARRING = 300;
	public final static int DEBUG_LEVEL_ERROR = 400;

	private static int debugLevel = -1;

	public static void debugInfo(String msg) {
		debug(DEBUG_LEVEL_INFO, msg);
	}

	public static void debugMsg(String msg) {
		debug(DEBUG_LEVEL_MSG, msg);
	}

	public static void debugWarring(String msg) {
		debug(DEBUG_LEVEL_WARRING, msg);
	}

	public static void debugError(String msg) {
		debug(DEBUG_LEVEL_ERROR, msg);
	}

	private static void debug(int level, String msg) {
		if (true || debugLevel == -1)
			debugLevel = getDebugLevel();
		if (debugLevel > level)
			return;
		try {
			throw new Exception(msg);
		} catch (Throwable logEx) {
			printDebug(System.currentTimeMillis(), logEx, true);
		}
	}

	public static void debug(Throwable logEx) {
		printDebug(System.currentTimeMillis(), logEx, false);
	}

	private static int getDebugLevel() {
		String level = "INFO";
		if ("INFO".equalsIgnoreCase(level)) {
			return DEBUG_LEVEL_INFO;
		} else if ("MSG".equalsIgnoreCase(level)) {
			return DEBUG_LEVEL_MSG;
		} else if ("WARRING".equalsIgnoreCase(level)) {
			return DEBUG_LEVEL_WARRING;
		} else if ("ERROR".equalsIgnoreCase(level)) {
			return DEBUG_LEVEL_ERROR;
		}
		return DEBUG_LEVEL_MSG;
	}

	private static void printDebug(long startTime, Throwable logEx, boolean isMsg) {
		synchronized (TRACE_DEBUG_FILE_NAME) {
			FileWriter writer = null;
			PrintWriter out = null;
			try {
				String prefix = PublicUtil.nullToEmpty(FrameworkUtil.getAbsolutePath(Constant.TRACE_DIRECTORY_PATH));
				String tracePath = "";
				if (prefix.equals("")) {
					tracePath = "log" + Constant.FILE_SEPARATOR + TRACE_DEBUG_FILE_NAME;
				} else {
					tracePath = prefix + TRACE_DEBUG_FILE_NAME;// 设置路径
				}
				final File dir = new File(tracePath).getParentFile();
				if (!dir.exists()) {
					dir.mkdirs();
				}

				File traceFile = new File(tracePath);

				if (!traceFile.exists()) {
					traceFile.createNewFile();
					shakeHandLogCleaner.filenew();
				} else if (traceFile.length() >= 102400) {// 100k
					String saveAsName = traceFile.getAbsolutePath() + "." + new Date().getTime();
					traceFile.renameTo(new File(saveAsName));
					traceFile.createNewFile();
					shakeHandLogCleaner.filenew();
				}

				writer = new FileWriter(traceFile, true);
				String time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(new Date(startTime)) + " ";

				out = new PrintWriter(writer);

				if (isMsg) {
					StackTraceElement[] statckTrace = logEx.getStackTrace();
					if (statckTrace.length > 2) {
						out.print(time);
						out.println("\tat " + statckTrace[1]);
						out.println(logEx.getMessage());

						/*PrintStream sysOut = System.out;
						if (sysOut instanceof DebugPrintStream) {
							sysOut = ((DebugPrintStream) sysOut).getSysPrintStream();
						}
						sysOut.print(time);
						sysOut.println("\tat " + statckTrace[1]);
						sysOut.println(logEx.getMessage());
						sysOut.println();*/
					}
				} else {
					logEx.printStackTrace(out);
					logEx.printStackTrace();
				}
				out.println();
			} catch (Exception e) {
				e.printStackTrace(System.err);
			} finally {
				try {
					if (out != null) {
						out.close();
						out = null;
					}
					if (writer != null) {
						writer.close();
						writer = null;
					}
				} catch (IOException e) {
				}
			}
		}
	}

	public static byte[] toUtf8(String s) {
		int size = 4 + s.length() + 1;
		ByteBuffer byteBuffer = ByteBuffer.allocate(size);
		char c;
		for (int i = 0; i < s.length(); i++) {
			c = s.charAt(i);
			if (c <= 0x007F) {
				byteBuffer.put((byte) c);
			} else if (c > 0x07FF) {
				byteBuffer.put((byte) (0xE0 | ((c >> 12) & 0x0F)));
				byteBuffer.put((byte) (0x80 | ((c >> 6) & 0x3F)));
				byteBuffer.put((byte) (0x80 | ((c >> 0) & 0x3F)));
			} else {
				byteBuffer.put((byte) (0xC0 | ((c >> 6) & 0x1F)));
				byteBuffer.put((byte) (0x80 | ((c >> 0) & 0x3F)));
			}
		}
		return byteBuffer.array();
	}

	public static String Utf8ToString(byte[] b) {

		String ret = "";
		try {
			ret = new String(b, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			// TODO 自动生成 catch 块
			e.printStackTrace();
		}

		return ret;
	}

	/**
	 * 从ip字符串转成数字
	 * 
	 * @param value
	 * @return
	 */
	public static long getIpFromString(String value) {
		String[] tmp = value.split("\\.");
		if (tmp.length != 4) {
			return 0;
		}

		String buffer = new String();
		for (int i = 3; i >= 0; i--) {
			int tmp_ = Integer.parseInt(tmp[i]);
			String tmp__ = Integer.toHexString(tmp_);

			if (tmp__.length() == 1) {
				tmp__ = "0" + tmp__;
			}

			buffer = tmp__ + buffer;

		}
		// for(String value_ : tmp){
		// int tmp_ = Integer.parseInt(value_);
		// String tmp__ = Integer.toHexString(tmp_);
		//
		// if(tmp__.length() == 1){
		// tmp__ = "0"+tmp__;
		// }
		//
		// buffer = tmp__+buffer;
		// }

		long tmp___ = Long.parseLong(buffer, 16);
		return tmp___;
	}

	/**
	 * 从Ip地址的数字转成ip
	 * 
	 * @param value
	 * @return
	 */
	public static String getIpFromNumber(long value) {
		try {
			if (true) {
				int[] ip = new int[4];

				int tmp = (int) value;
				String tmp_ = Integer.toHexString(tmp);
				while (tmp_.length() < 8) {
					//
					tmp_ = "0" + tmp_;
				}

				for (int i = 0; i < 4; i++) {
					int j = i * 2;
					String tmp__ = tmp_.substring(j, j + 2);
					int tmp___ = Integer.parseInt(tmp__, 16);

					ip[i] = tmp___;
				}

				String ip_ = "";
				for (int j = 0; j <= 3; j++) {
					ip_ = ip_ + String.valueOf(ip[j]);

					if (j != 3) {
						ip_ = ip_ + ".";
					}
				}

				return ip_;
			}
		} catch (Exception e) {
			// TODO: handle exception
		}

		return null;
	}

	/**
	 * 取得运行工程的绝对路径的上个路径,创建tmp目录
	 * 
	 * @return
	 */
	private static String rcpPath_Tmp = null;

	public static String getRCPPath_Tmp() {
		if (rcpPath_Tmp == null) {
			String path = SystemUtil.getSystemPath();

			// 判断是否有中文
			if (path.length() == path.getBytes().length) {
				// 无中文路径
			} else {
				//
				int index = path.lastIndexOf("/");

				path = path.substring(0, index);

				index = path.lastIndexOf("/");
				path = path.substring(0, index);
				path = path + "/";
			}

			rcpPath_Tmp = path + "tmp";

			try {
				File dir = new File(rcpPath_Tmp);
				if (!dir.exists()) {
					dir.mkdir();
				}
			} catch (Exception e) {
				// TODO: handle exception
			}
		}

		return rcpPath_Tmp + "/";
	}

	/**
     * 
     */
	public static List sortListByChina(List list) {
		// 排序// 排序
		Comparator cmp = Collator.getInstance(java.util.Locale.CHINA);
		// 枚举根据描述进行排序

		try {
			Collections.sort(list, cmp);
		} catch (Exception e) {

		}

		return list;
	}

}
